package com.ruoyi.system.mybatis.handler;


import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@AllArgsConstructor
public class TenantContextHolderFilter extends GenericFilterBean {


    @Autowired
    private TokenHandlerService tokenHandlerService;

    @Autowired
    private RedisCache redisCache;

    @Override
    @SneakyThrows
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        try {
            //获取到用户信息
            LoginUser loginUser = tokenHandlerService.getLoginUser(request);
            //判断用户是否不为空
            if(Objects.nonNull(loginUser)){
                if(loginUser.getUser().getUserType().equals("11")){
                    TenantContextHolder.setUserRole("admin");
                }else {
                    TenantContextHolder.setUserRole("user");
                }
                //存放租户id
                if(Objects.nonNull(loginUser.getUser().getTenantId())){
                    TenantContextHolder.setTenantId(Integer.valueOf(loginUser.getUser().getTenantId()));
                }else {
                    TenantContextHolder.setTenantId(0);
                }
            }else {
                TenantContextHolder.setTenantId(0);
            }
            log.info("获取到的租户ID为:{}", TenantContextHolder.getTenantId());
            filterChain.doFilter(request, response);
        } finally {
            TenantContextHolder.clear();
        }
    }




}
